from app import app, db, admin
from app.forms import LoginForm, RegistrationForm
from flask import request, render_template, flash, redirect, url_for
from flask_login import current_user, login_user, logout_user, login_required
from app.models import User, Suggestions, Votes
from werkzeug.urls import url_parse
from sqlalchemy.exc import IntegrityError


@app.route('/')
@app.route('/index')
@login_required
def index():
    suggestions = Suggestions.query.all()
    return render_template("index.html",
                           title='Home Page',
                           suggestions=suggestions,
                           admin=admin)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('login.html', title='Sign In', form=form)


@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))


@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)


@app.route('/user/<username>')
@login_required
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    suggestions = Suggestions.query.filter_by(author=user).all()
    return render_template('user.html', user=user,
                            suggestions=suggestions, admin=admin)


@app.route('/add', methods=['POST'])
def add():
    name = request.values.get('name')
    if name is '':
        flash('Aaa empty body of suggestion!')
        return redirect('/')
    sugg_exists = Suggestions.query.filter_by(
            body=name).first() is not None
    if sugg_exists:
        flash('Aaaa suggestion already exists!')
        return redirect('/')
    comment = request.values.get('comment')
    print(len(name), len(comment))
    if len(name) >= 140 or len(comment) >= 140:
        flash('Aaaa too long message!')
        return redirect('/')
    suggestion = Suggestions(body=name, author=current_user, comment=comment)
    db.session.add(suggestion)
    db.session.commit()
    return redirect('/')


@app.route('/remove/<user>/<sugg_id>', methods=['POST'])
def remove(user, sugg_id):
    if user != current_user.username and current_user.username != admin:
        flash('You can delete only your suggestions!')
        return redirect('/user/{}'.format(current_user.username))
    s = Suggestions.query.get(sugg_id)
    votes = Votes.query.filter_by(sugg_id=sugg_id).all()
    for v in votes:
        db.session.delete(v)
    db.session.delete(s)
    db.session.commit()
    return redirect('/user/{}'.format(user))


@app.route('/delete_profile/<username>', methods=['POST'])
def delete_profile(username):
    if username != current_user.username and current_user.username != admin:
        flash('What are you doing....')
        return redirect('/user/{}'.format(username))
    if current_user.username != admin:
        logout_user()
    user = User.query.filter_by(username=username).first_or_404()
    suggs = Suggestions.query.filter_by(author=user).all()
    votes = Votes.query.filter_by(user_id=user.id).all()
    for s in suggs:
        votes_for_user_suggs = Votes.query.filter_by(sugg_id=s.id).all()
        for v in votes_for_user_suggs:
            db.session.delete(v)
        db.session.delete(s)
    for v in votes:
        db.session.delete(v)
    db.session.delete(user)
    db.session.commit()
    return redirect('/')


@app.route('/confirm_deletion/<username>', methods=['POST'])
def confirm_deletion(username):
    user = User.query.filter_by(username=username).first_or_404()
    return render_template('confirm_deletion.html', user=user)


@app.route('/vote/<user>/<sugg_id>', methods=['POST'])
def vote(user, sugg_id):
    if user is current_user.username:
        flash('You cannot vote only for your suggestions!')
        return redirect('/')
    v = Votes(user_id=current_user.id, sugg_id=sugg_id)
    try:
        db.session.add(v)
        db.session.commit()
    except IntegrityError:
        flash('You cannot vote only once!')
        return redirect('/')
    return redirect('/')


@app.route('/unvote/<user>/<sugg_id>', methods=['POST'])
def unvote(user, sugg_id):
    if user is current_user.username and current_user != admin:
        flash('You cannot unvote only your suggestions!')
        return redirect('/')
    v = Votes.query.filter_by(user_id=current_user.id, sugg_id=sugg_id).first()
    db.session.delete(v)
    db.session.commit()
    return redirect('/')


@app.route('/edit/<user>/<sugg_id>', methods=['POST'])
def edit(user, sugg_id):
    if user != current_user.username and current_user.username != admin:
        flash('You can edit only your suggestions!')
        return redirect('/user/{}'.format(current_user.username))
    name = request.values.get('name')
    comment = request.values.get('comment')
    s = Suggestions.query.get(sugg_id)
    s.name = name
    s.comment = comment
    db.session.commit()
    return redirect('/user/{}'.format(user))
    # s = Suggestions.query.get(sugg_id)
    # votes = Votes.query.filter_by(sugg_id=sugg_id).all()
    # for v in votes:
    #     db.session.delete(v)
    # db.session.delete(s)
    # db.session.commit()
    # return redirect('/user/{}'.format(current_user.username))



# EOF

